package com.example.myblog.controller;

import com.example.myblog.model.Category;
import com.example.myblog.model.Post;
import com.example.myblog.service.CategoryService;
import com.example.myblog.service.MarkdownService;
import com.example.myblog.service.PostService;
import com.example.myblog.service.SettingsService;
import com.example.myblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.Map;

/**
 * 处理文章相关Web请求的控制器
 */
@Controller
public class PostController {

    @Autowired
    private PostService postService;
    
    @Autowired
    private MarkdownService markdownService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CategoryService categoryService;
    
    @Autowired
    private SettingsService settingsService;
    
    /**
     * 显示博客首页，展示所有文章列表
     */
    @GetMapping("/")
    public String index(Model model) {
        // 获取所有文章并生成摘要
        var posts = postService.getAllPosts();
        posts.forEach(post -> {
            String summary = markdownService.generateSummary(post.getContent(), 150);
            post.setSummary(summary);
        });
        
        model.addAttribute("posts", posts);
        model.addAttribute("categories", categoryService.getAllCategories());
        model.addAttribute("activeCategory", null);
        model.addAttribute("topViewedPosts", postService.getTopViewedPosts());
        
        // 添加背景图片设置
        String backgroundImage = settingsService.getSettingValueByKey("background_image", "");
        model.addAttribute("backgroundImage", backgroundImage);
        
        // 添加当前用户信息和权限
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !auth.getName().equals("anonymousUser")) {
            model.addAttribute("isAdmin", userService.isAdmin(auth.getName()));
            model.addAttribute("currentUser", userService.getUserByUsername(auth.getName()));
        }
        
        return "index";
    }
    
    /**
     * 按分类显示文章列表
     */
    @GetMapping("/category/{id}")
    public String listPostsByCategory(@PathVariable Long id, Model model) {
        Category category = categoryService.getCategoryById(id);
        if (category == null) {
            return "redirect:/";
        }
        
        // 获取分类文章并生成摘要
        var posts = postService.getPostsByCategory(category);
        posts.forEach(post -> {
            String summary = markdownService.generateSummary(post.getContent(), 150);
            post.setSummary(summary);
        });
        
        model.addAttribute("posts", posts);
        model.addAttribute("categories", categoryService.getAllCategories());
        model.addAttribute("activeCategory", category);
        model.addAttribute("topViewedPosts", postService.getTopViewedPostsByCategory(category));
        
        // 添加背景图片设置
        String backgroundImage = settingsService.getSettingValueByKey("background_image", "");
        model.addAttribute("backgroundImage", backgroundImage);
        
        // 添加当前用户信息和权限
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !auth.getName().equals("anonymousUser")) {
            model.addAttribute("isAdmin", userService.isAdmin(auth.getName()));
            model.addAttribute("currentUser", userService.getUserByUsername(auth.getName()));
        }
        
        return "index";
    }
    
    /**
     * 显示文章详情页
     */
    @GetMapping("/posts/{id}")
    public String showPost(@PathVariable Long id, Model model) {
        Post post = postService.getPostById(id);
        if (post == null) {
            return "redirect:/";
        }
        
        // 将Markdown内容转换为HTML
        String htmlContent = markdownService.convertToHtml(post.getContent());
        post.setContent(htmlContent);
        
        model.addAttribute("post", post);
        model.addAttribute("categories", categoryService.getAllCategories());
        
        // 添加当前用户信息和权限
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !auth.getName().equals("anonymousUser")) {
            model.addAttribute("isAdmin", userService.isAdmin(auth.getName()));
            model.addAttribute("currentUser", userService.getUserByUsername(auth.getName()));
        }
        
        return "detail";
    }
    
    /**
     * 显示创建文章的表单页面
     * 需要ADMIN角色
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/posts/new")
    public String showCreateForm(Model model) {
        model.addAttribute("post", new Post());
        model.addAttribute("categories", categoryService.getAllCategories());
        model.addAttribute("isNew", true);
        return "form";
    }
    
    /**
     * 处理创建文章的POST请求
     * 先调用OssService上传图片并获取URL，再将该URL连同其他文章信息一起存入数据库
     * 需要ADMIN角色
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/posts/new")
    public String createPost(@ModelAttribute Post post, 
                           @RequestParam("imageFile") MultipartFile imageFile,
                           @RequestParam(value = "markdownContent", required = false) String markdownContent,
                           @RequestParam(value = "categoryId", required = false) Long categoryId,
                           RedirectAttributes redirectAttributes) {
        // 使用Markdown内容作为文章内容
        if (markdownContent != null && !markdownContent.isEmpty()) {
            post.setContent(markdownContent);
        }
        try {
            // 获取当前用户名
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String username = auth.getName();
            
            // 设置分类
            if (categoryId != null) {
                Category category = categoryService.getCategoryById(categoryId);
                post.setCategory(category);
            }
            
            // 创建文章，包括上传图片到OSS
            Post savedPost = postService.createPost(post, imageFile, username);
            redirectAttributes.addFlashAttribute("message", "文章创建成功！");
            return "redirect:/posts/" + savedPost.getId();
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "文章创建失败：" + e.getMessage());
            return "redirect:/posts/new";
        }
    }
    
    /**
     * 显示编辑文章的表单页面
     * 需要ADMIN角色
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/posts/{id}/edit")
    public String showEditForm(@PathVariable Long id, Model model) {
        Post post = postService.getPostById(id);
        if (post == null) {
            return "redirect:/";
        }
        model.addAttribute("post", post);
        model.addAttribute("categories", categoryService.getAllCategories());
        model.addAttribute("isNew", false);
        model.addAttribute("markdownContent", post.getContent()); // 原始Markdown内容
        return "form";
    }
    
    /**
     * 处理更新文章的POST请求
     * 需要ADMIN角色
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/posts/{id}/edit")
    public String updatePost(@PathVariable Long id,
                           @ModelAttribute Post post,
                           @RequestParam(value = "imageFile", required = false) MultipartFile imageFile,
                           @RequestParam(value = "markdownContent", required = false) String markdownContent,
                           @RequestParam(value = "categoryId", required = false) Long categoryId,
                           @RequestParam(value = "deleteImage", required = false, defaultValue = "false") String deleteImage,
                           RedirectAttributes redirectAttributes) {
        // 使用Markdown内容作为文章内容
        if (markdownContent != null && !markdownContent.isEmpty()) {
            post.setContent(markdownContent);
        }
        try {
            // 获取当前用户名
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String username = auth.getName();
            
            // 设置分类
            if (categoryId != null) {
                Category category = categoryService.getCategoryById(categoryId);
                post.setCategory(category);
            }
            
            // 检查是否需要删除图片
            boolean shouldDeleteImage = "true".equals(deleteImage);
            
            // 更新文章，如果有新图片则上传到OSS
            Post updatedPost = postService.updatePost(id, post, imageFile, username, shouldDeleteImage);
            if (updatedPost == null) {
                redirectAttributes.addFlashAttribute("error", "文章不存在！");
                return "redirect:/";
            }
            redirectAttributes.addFlashAttribute("message", "文章更新成功！");
            return "redirect:/posts/" + updatedPost.getId();
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "文章更新失败：" + e.getMessage());
            return "redirect:/posts/" + id + "/edit";
        }
    }
    
    /**
     * 处理删除文章的请求
     * 需要ADMIN角色
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/posts/{id}/delete")
    public String deletePost(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            postService.deletePost(id);
            redirectAttributes.addFlashAttribute("message", "文章删除成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "文章删除失败：" + e.getMessage());
        }
        return "redirect:/";
    }
    
    /**
     * 处理编辑器内图片上传的API接口
     * 需要ADMIN角色
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/api/upload-image")
    @ResponseBody
    public Map<String, Object> uploadImage(@RequestParam("image") MultipartFile imageFile) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证文件类型
            if (imageFile.isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择要上传的图片");
                return response;
            }
            
            String contentType = imageFile.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                response.put("success", false);
                response.put("message", "只能上传图片文件");
                return response;
            }
            
            // 验证文件大小 (限制为5MB)
            if (imageFile.getSize() > 5 * 1024 * 1024) {
                response.put("success", false);
                response.put("message", "图片大小不能超过5MB");
                return response;
            }
            
            // 获取当前用户名
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String username = auth.getName();
            
            // 上传图片到OSS并获取URL
            String imageUrl = postService.uploadImageToOSS(imageFile, username);
            
            response.put("success", true);
            response.put("url", imageUrl);
            response.put("message", "图片上传成功");
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "图片上传失败：" + e.getMessage());
        }
        
        return response;
    }
    

}